<template>
  <div>
    <div class="flex items-center justify-center gap-2">
      <div class="name">设置名称： </div>
      <Input style="width: 160px" v-model:value="dataRef.name" />
    </div>
    <Card title="主表" :bordered="false">
      <template v-if="isBatch">
        <Table :data-source="dataRef.dataSource" :columns="mainColumns" :pagination="false">
          <template #bodyCell="{ record, column }">
            <template v-if="column.dataIndex == 'name'">
              <Select
                style="width: 100%"
                v-model:value="record[column.dataIndex]"
                show-search
                optionFilterProp="label"
                :options="[
                  {
                    value: '',
                    label: '不导入',
                  },
                  ...formGetFieldsData,
                ]"
              />
            </template>
          </template>
        </Table>
      </template>
      <template v-else>
        <table cellSpacing="0" cellPadding="3" width="100%" align="center" class="tabStyle_1">
          <tr class="cell" v-for="(item, tri) in dataRef.cells" :key="`tr${tri}`">
            <td
              v-for="(el, tdi) in item"
              :key="`tr${tdi}`"
              :class="{ td_selected_bg: el.name ? true : false }"
              @dblclick="handleDBLClick(el, tri, tdi)"
            >
              <pre>{{ el.fieldName || el.title }}</pre>
            </td>
          </tr>
        </table>
      </template>
    </Card>
    <Card title="主表基础数据清洗" :bordered="false">
      <div v-for="(item, index) in dataRef.basicFields" :key="index" style="margin-bottom: 10px">
        <checkbox style="margin-bottom: 10px" v-model:checked="item.checked">
          {{ item.title }} （勾选后才能清洗数据）
        </checkbox>
        <Table :data-source="item.options" :columns="childColumns" :pagination="false">
          <template #bodyCell="{ record, column }">
            <template v-if="column.dataIndex == 'otherVal'">
              <Input style="width: 100%" v-model:value="record[column.dataIndex]" />
            </template>
          </template>
        </Table>
      </div>
    </Card>
    <div class="text-center m-2">
      <a-button type="primary" @click="handleSubmit" :loading="loading">确定</a-button>
    </div>
    <Modal v-model:visible="visible" title="设置">
      <div class="flex gap-10px justify-center m-10px">
        <div>表单域：</div>
        <div>
          <Select
            style="width: 200px"
            v-model:value="currentCode"
            show-search
            optionFilterProp="label"
            :options="formGetFieldsData"
          />
        </div>
      </div>
      <template #footer>
        <a-button type="primary" @click="handleOk(currentCode)">确定</a-button>
        <a-button type="primary" @click="handleOk('')">恢复</a-button>
        <a-button @click="visible = false">取消</a-button>
      </template>
    </Modal>
  </div>
</template>
<script lang="ts" setup>
  import { ref, watch, nextTick } from 'vue';
  import { Input, Card, Table, Select, Checkbox, Modal } from 'ant-design-vue';
  import { mainColumns, childColumns } from './importComponentEdit.data';
  import { isArray, isEmpty } from '/@/utils/is';
  import { getFieldsWithRelated } from '/@/api/flowManage/flowManage';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { cloneDeep } from 'lodash-es';
  const props = defineProps({
    stateData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    formCode: {
      type: String,
      default: '',
    },
    isBatch: {
      type: Boolean,
      default: true,
    },
    loading: {
      type: Boolean,
      default: false,
    },
    isUpdate: {
      type: Boolean,
      default: false,
    },
  });
  const emit = defineEmits(['success']);
  const { createMessage, createConfirm } = useMessage();
  const dataRef = ref<Recordable>({
    dataSource: [],
    cells: [],
    basicFields: [],
    name: '',
  });
  watch(
    () => props.stateData,
    async (newVal) => {
      console.log('newVal', newVal);
      if (isEmpty(newVal)) return;
      await nextTick();
      const newVals = cloneDeep(newVal);
      const { name, cols, cells, basicFields } = newVals;
      dataRef.value.dataSource = [];
      dataRef.value.basicFields = [];
      dataRef.value.cells = [];
      dataRef.value.name = name ?? '';
      await getFormGetFieldsData();
      if (cols && isArray(cols)) {
        dataRef.value.dataSource = cols;
        if (!props.isUpdate) {
          dataRef.value.dataSource.forEach((item) => {
            item.name =
              formGetFieldsData.value.find((el) => el.label.indexOf(item.title) != -1)?.value ?? '';
          });
        }
      }
      if (cells && isArray(cells)) {
        dataRef.value.cells = cells;
        if (props.isUpdate) {
          dataRef.value.cells.forEach((item) => {
            if (item && item.length) {
              item.forEach((el) => {
                el.title = el.title ? el.title.replaceAll('&#', '\n') : '';
                el.fieldName =
                  formGetFieldsData.value.find((f) => f.value === el.name)?.label ?? '';
              });
            }
          });
        }
      }
      if (basicFields && isArray(basicFields) && basicFields?.length) {
        dataRef.value.basicFields = basicFields;
      }
      console.log('dataRef', dataRef.value);
    },
    {
      immediate: true,
      deep: true,
    },
  );
  const visible = ref(false);
  const currentCode = ref(''); //当前的表单code
  const currentRecord = ref<Recordable>({});
  //双击打开选择
  const handleDBLClick = (el, tri, tdi) => {
    currentRecord.value = {
      el,
      tri,
      tdi,
    };
    currentCode.value =
      el.name || (formGetFieldsData.value.length ? formGetFieldsData.value[0].value : '');
    visible.value = true;
  };

  const handleOk = (val) => {
    dataRef.value.cells.forEach((item, index) => {
      if (index == currentRecord.value.tri) {
        item.forEach((el, eli) => {
          if (eli == currentRecord.value.tdi) {
            el.name = val;
            el.fieldName = val
              ? formGetFieldsData.value.find((item) => item.value == val)?.label
              : '';
          }
        });
      }
    });
    visible.value = false;
  };

  const handleSubmit = () => {
    if (!dataRef.value.name) {
      createMessage.warning('名称不能为空');
      return;
    }
    console.log('handleSubmit dataRef.value', dataRef.value);
    emit('success', dataRef.value);
  };
  const formGetFieldsData = ref<Recordable[]>([]);
  //获取数据
  const getFormGetFieldsData = async () => {
    formGetFieldsData.value = [];
    try {
      if (!props.formCode) return;
      await getFieldsWithRelated({ formCode: props.formCode }).then((res) => {
        formGetFieldsData.value = res || [];
        formGetFieldsData.value.forEach((item: Recordable) => {
          delete item.options;
          item.value = item.name;
          item.label = item.title;
        });
      });
    } catch (err) {
      console.log('getFieldsWithRelated', err);
    }
  };
</script>
<style scoped>
  .name::before {
    display: inline-block;
    margin-right: 4px;
    color: #ff4d4f;
    font-size: 14px;
    font-family: SimSun, sans-serif;
    line-height: 1;
    content: '*';
  }
  .td_selected_bg {
    background-color: #00cc00;
  }
  .tabStyle_1 td {
    padding: 2px 7px;
  }
</style>
